﻿using BaseAuthRole.Domain.Input;
using BaseAuthRole.DTO.User;
using BaseAuthRole.IService;
using BaseAuthRole.Web.Filters;
using log4net;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using RS.BaseModel.Common;
using RS.Environment;
using RS.Tool.Base;
using RS.Tool.Init;
using System.Web;

namespace BaseAuthRole.Web.Controllers
{
    [Route("[controller]/[action]")]
    public class OAuth2Controller : Controller
    {
        private IApplicationService _applictationService;

        private IUserService _userService;

        private static ILog logger = log4net.LogManager.GetLogger("OAuth2Controller");
        public OAuth2Controller(IApplicationService applictationService, IUserService userService)
        {
            this._applictationService = applictationService;

            this._userService = userService;
        }


        [AuthCheckFilter]
        public ActionResult PublicAppAuthorize([FromQuery] PublicAppAuthorizeIput publicAppAuthorizeIput)
        {

            logger.Info("PublicAppAuthorize:"+Request.Path.ToString());

            var userloginInfo = UserCookieHelper.GetCookieUserInfo();

            if (string.IsNullOrEmpty(publicAppAuthorizeIput.AppId) || string.IsNullOrEmpty(publicAppAuthorizeIput.Scope) || string.IsNullOrEmpty(publicAppAuthorizeIput.RedirectUri))
            {
                return Redirect(ConfigurationHelper.GetAppSettings("noresource_url"));
            }

            var app = this._applictationService.GetApplicationModel(publicAppAuthorizeIput.AppId);

            if (app == null)
            {
                return Redirect(ConfigurationHelper.GetAppSettings("error_url"));
            }
            if (app.Status != 1)
            {
                return Redirect(ConfigurationHelper.GetAppSettings("error_url"));
            }

            var scope_list = publicAppAuthorizeIput.Scope.Split(',').ToList();

            var scope_name_list = new List<string>();

            foreach (var o in scope_list)
            {
                scope_name_list.Add(EnumHelper.GetDescription((UUIUserAuthType)Enum.Parse(typeof(UUIUserAuthType), o)));
            }

            var check_r = this._userService.PublicAppAuthorizeCheck(publicAppAuthorizeIput.AppId, userloginInfo.Id, publicAppAuthorizeIput.Scope, publicAppAuthorizeIput.RedirectUri);

            if (check_r.IsError)
            { 
                return Redirect($"{ConfigurationHelper.GetAppSettings("error_url")}?message={HttpUtility.UrlEncode(check_r.Message)}");
            }


            ViewData["PublicAppAuthorizeIput"] = publicAppAuthorizeIput;
            ViewData["User"] = check_r.Result;
            ViewData["App"] = app;
            ViewData["ScopeNameList"] = scope_name_list;

            return PartialView();
        }

        [PageAuthCheckFilter]
        [HttpPost]
        public string AuthorizeDo([FromForm] AuthorizeDoInput authorizeDoInput)
        {
            var userloginInfo = UserCookieHelper.GetCookieUserInfo();

            var result = new CommonResult();          

             if (string.IsNullOrEmpty(authorizeDoInput.AppId) || string.IsNullOrEmpty(authorizeDoInput.Scope) || string.IsNullOrEmpty(authorizeDoInput.RedirectUri))
            {
                result.Value = RS.BaseModel.Enum.EnumBaseResult.KeyParaMiss;
                result.Message = "必要参数缺失";

                return JsonConvert.SerializeObject(result);

            }           

            //开始授权
            var auth_r = this._userService.GetUserAuthCode(authorizeDoInput.AppId, userloginInfo.Id, authorizeDoInput.Scope, authorizeDoInput.RedirectUri);

            if (auth_r.IsError){

                return JsonConvert.SerializeObject(result);
            }
            else {

                if (authorizeDoInput.RedirectUri.Contains("?"))
                {
                    authorizeDoInput.RedirectUri += "&auth_code=" + auth_r.Result;
                }
                else
                {
                    authorizeDoInput.RedirectUri += "?auth_code=" + auth_r.Result;
                }

                auth_r.Result = authorizeDoInput.RedirectUri;

                return JsonConvert.SerializeObject(auth_r);

            }
        }

    }
}
